import db from './mysqlHelper.js';
import moment from 'moment';
import schedule from 'node-schedule';
import { DEVICES } from "./publicValue.js";




async function writeUsedHour() {
    let sqls = [];

    let now = moment('2024-10-24 14:00:00');
    let startTime = now.format('YYYY-MM-DD HH:00:00');
    let endTime = now.format('YYYY-MM-DD HH:59:59');

    let sql = `select * from device`;
    let res = await db.query(sql);

    for (const key of res) {
        let device = key;
        let startRecord = await db.findAllNoPage('used', { sn: device.sn, write_time: startTime }, '', '', 1, 0,);
        if (startRecord.length > 0) {
            startRecord[0].total_flow = startRecord[0].end_value;
            startRecord[0].read_time = startRecord[0].end_time;
        } else {
            startRecord = await db.findAllNoPage('history', { sn: device.sn }, 'read_time', 'asc', 1, 0, [{ field: 'read_time', start: startTime, end: endTime }]);
        }
        let endRecord = await db.findAllNoPage('history', { sn: device.sn }, 'read_time', 'desc', 1, 0, [{ field: 'read_time', start: startTime, end: endTime }]);
        if (startRecord.length == 0 || endRecord.length == 0) {
            console.log(device.sn, '缺少历史数据取消用量统计');
            continue;
        }
        else {
            let used = {
                sn: device.sn,
                project_id: device.project_id,
                device_name: device.name,
                write_time: moment('2024-10-24 15:00:00').format('YYYY-MM-DD HH:00:00'),
                start_time: startRecord[0].read_time,
                end_time: endRecord[0].read_time,
                start_value: startRecord[0].total_flow,
                end_value: endRecord[0].total_flow,
                total: endRecord[0].total_flow - startRecord[0].total_flow,
                device_type: startRecord[0].device_type
            }
            sqls.push({ sql: `INSERT INTO used SET ?`, param: [used] });
        }

    }
    if (sqls.length > 0) {
        let res = await db.transaction(sqls);
        if (res instanceof Error) {
            console.error('每小时统计数据写入失败', res.message, JSON.stringify(sqls));
            return;
        }
        console.log(`每小时统计数据写入成功`);
    }
}

async function writeUsedDay(now) {
    let sqls = [];
    console.log('开始写入日用量表', now.format('YYYY-MM-DD HH:mm:ss'));
    let endTime = now.format('YYYY-MM-DD 00:00:01');
    now = now.subtract(1, 'days');
    let startTime = now.format('YYYY-MM-DD 00:00:01');
    let sql = `select * from device`;
    let res = await db.query(sql);
    for (let i = 0; i < res.length; i++) {
        let device = res[i];
        let startRecord = await db.findAllNoPage('used', { sn: device.sn }, 'write_time', 'asc', 1, 0, [{ field: 'write_time', start: startTime, end: endTime }]);
        let endRecord = await db.findAllNoPage('used', { sn: device.sn }, 'write_time', 'desc', 1, 0, [{ field: 'write_time', start: startTime, end: endTime }]);
        if (startRecord.length == 0 || endRecord.length == 0) {
            console.log(device.sn, '缺少历史数据取消用量统计');
            continue;
        }
        else {
            let used = {
                sn: device.sn,
                project_id: device.project_id,
                device_name: device.name,
                write_time: now.format('YYYY-MM-DD 00:00:01'),
                start_time: startRecord[0].start_time,
                end_time: endRecord[0].end_time,
                start_value: startRecord[0].start_value,
                end_value: endRecord[0].end_value,
                total: endRecord[0].end_value - startRecord[0].start_value,
                device_type: startRecord[0].device_type
            }
            sqls.push({ sql: `INSERT INTO used_day SET ?`, param: [used] });
        }
    }

    // for (const key of memDB.Devcies.keys()) {
    //     let device = memDB.getDevice(key);

    // }
    if (sqls.length > 0) {
        let res = await db.transaction(sqls);
        if (res instanceof Error) {
            console.error('日用量表写入失败', res.message, JSON.stringify(sqls));
            return;
        }
        console.log(`日用量表写入成功`);
    }
}

async function writeUsedMonth(now) {
    let sqls = [];
    let endTime = now.format('YYYY-MM-01 00:00:00');
    now = now.subtract(1, 'months');
    let startTime = now.format('YYYY-MM-01 00:00:01');
 
    let sql = `select * from device`;
    let res = await db.query(sql);
    for (let i = 0; i < res.length; i++) {
        let device = res[i];
        let startRecord = await db.findAllNoPage('used_day', { sn: device.sn }, 'write_time', 'asc', 1, 0, [{ field: 'write_time', start: startTime, end: endTime }]);
        let endRecord = await db.findAllNoPage('used_day', { sn: device.sn }, 'write_time', 'desc', 1, 0, [{ field: 'write_time', start: startTime, end: endTime }]);
        if (startRecord.length == 0 || endRecord.length == 0) {
            console.log(device.sn, '缺少历史数据取消用量统计');
            continue;
        }
        else {
            let used = {
                sn: device.sn,
                device_name: device.name,
                project_id: device.project_id,
                write_time: now.format('YYYY-MM-01 00:00:01'),
                start_time: startRecord[0].start_time,
                end_time: endRecord[0].end_time,
                start_value: startRecord[0].start_value,
                end_value: endRecord[0].end_value,
                total: endRecord[0].end_value - startRecord[0].start_value,
                device_type: startRecord[0].device_type
            }
            sqls.push({ sql: `INSERT INTO used_month SET ?`, param: [used] });
        }
    }
    if (sqls.length > 0) {
        let res = await db.transaction(sqls);
        if (res instanceof Error) {
            console.error('月用量表写入失败', res.message, JSON.stringify(sqls));
            return;
        }
        console.log(`月用量表写入成功`);
    }
}



async function test() {
    // let now = moment('2024-08-01 00:00:00');


    // // while (now.isBefore(moment())) {
    // //     console.log(now.format('YYYY-MM-DD HH:mm:ss'));
    // //     await writeUsedDay(now);
    // //     now = now.add(2, 'days');
    // // }
    // while (now.isBefore(moment())) {
    //     console.log(now.format('YYYY-MM-DD HH:mm:ss'));
    //     await writeUsedMonth(now);
    //     now = now.add(2, 'months');
    // }

    writeUsedHour();

}

test();